﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using HomeDms.Properties;
using HomeDmsUtils;
using HomeDms.Imaging;
using ImageAcquisitionTAL;

namespace HomeDms
{
    public partial class FirstTimeForm : Form
    {
        public FirstTimeForm()
        {
            InitializeComponent();
        }

        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            createDBDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            if (createDBDialog.ShowDialog(this) == DialogResult.OK)
            {
                DBPathTextBox.Text = createDBDialog.FileName;
            }
        }

        private void createDBDialog_FileOk(object sender, CancelEventArgs e)
        {
            DBPathTextBox.Text = createDBDialog.FileName;
            e.Cancel = !ValidateDBPath();
        }

        internal string DBPath
        {
            get
            {
                return DBPathTextBox.Text;
            }
        }

        internal ColorMode ColorMode
        {
            get
            {
                ColorMode cm = ColorMode.BW;
                if (scannersCombobox1.SelectedScannerInfo.SupportsBW)
                    cm = ColorMode.BW;
                else if (scannersCombobox1.SelectedScannerInfo.SupportsGrayScale)
                    cm = ColorMode.GrayScale;
                else if (scannersCombobox1.SelectedScannerInfo.SupportsColors)
                    cm = ColorMode.Color;
                else
                    Localizer.MsgBox(this, "Wrong scanner color mode. Please, change it via Database->Preferences... menu.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return cm;
            }
        }

        internal string Scanner
        {
            get
            {
                return scannersCombobox1.SelectedDeviceID;
            }
        }

        internal int Language
        {
            get
            {
                return listBox1.SelectedIndex;
            }
        }

        IAcquisitionTechnology[] technologies = null;

        private ScannerInfo GetBestScanner()
        {
            ScannerInfo selected = null;
            try
            {
                technologies = ImageAcquisitionTechnologyFactory.GetSupportedTechnologies();
                selected = TryBestInTechnology("Microsoft WIA 2.0");
                if (selected != null)
                    return selected;
                selected = TryBestInTechnology("Microsoft WIA 1.0");
                if (selected != null)
                    return selected;
                selected = TryBestInTechnology("TWAIN");
                if (selected != null)
                    return selected;
                selected = GetAnyScanner();
            }
            catch
            {
                selected = GetAnyScanner();
            }            
            return selected;
        }

        private ScannerInfo TryBestInTechnology(string tech)
        {
            IAcquisitionTechnology t = GetAvailableTechnology(tech);
            if (t != null)
                return GetBestScannerInTechnology(t);
            else
                return null;
        }

        private ScannerInfo GetAnyScanner()
        {
            foreach (IAcquisitionTechnology t in technologies)
            {
                IEnumerable<ScannerInfo> scanners = t.GetInstalledScanners();
                if (scanners.Count<ScannerInfo>() > 0)
                    return scanners.ElementAt<ScannerInfo>(0);
            }
            return null;
        }

        private IAcquisitionTechnology GetAvailableTechnology(string techName)
        {
            foreach (IAcquisitionTechnology tech in technologies)
            {
                if (tech.Name == techName)
                    return tech;
            }
            return null;
        }

        private ScannerInfo GetBestScannerInTechnology(IAcquisitionTechnology t)
        {
            // for a while - the best is which has sheet feeder
            try
            {
                foreach (ScannerInfo info in t.GetInstalledScanners())
                {
                    ScannerInfo info1 = t.GetScannerInfo(info.DeviceID);
                    if (info1.SupportsFeeder)
                    {
                        return info1;
                    }
                }
            }
            catch
            {
                return null;
            }
            return null;
        }

        private void FirstTimeForm_Load(object sender, EventArgs e)
        {
            listBox1.SelectedIndex = Settings.Default.UILanguage;
            listBox1.SelectedIndexChanged += new EventHandler(listBox1_SelectedIndexChanged);
            ScannerInfo scanner = GetBestScanner();
            if (scanner != null)
            {
                scannersCombobox1.SelectedDeviceID = scanner.DeviceID;
                DBPathTextBox.Text = Path.Combine(
                    Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
                    "Bind`n`find.sdf"); 
            }
        }

        private bool ValidateDBPath()
        {
            bool bad = File.Exists(DBPath);
            if (bad)
                Localizer.MsgBox(this, "File '{0}' is already exists and may contain your database with documents. Please use another database name, or delete or rename existing file manually.",
                    "Create new database", MessageBoxButtons.OK, MessageBoxIcon.Warning, DBPath);
            return !bad;
        }

        private void FirstTimeForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (DialogResult == DialogResult.OK)
                e.Cancel = !ValidateDBPath();
        }

        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            Settings.Default.UILanguage = listBox1.SelectedIndex;
            Settings.Default.Save();
            DialogResult = DialogResult.Retry;
        }

        private void FirstTimeForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (DialogResult == DialogResult.OK)
            {
                Settings.Default.DefaultColorMode = ColorMode;
                Settings.Default.DefaultResolution = 200;
                Settings.Default.DefaultScanner = Scanner;
                Settings.Default.UILanguage = Language;
                Settings.Default.Save();
            }
        }

    }
}
